import { defineStore } from "pinia";
interface SnapShotState {
  snapshotData: any[];
  maxStep: number;
  curIndex: number;
  isSnapshot: boolean;
}
export const useSnapShotStore = defineStore("snapShot", {
  state: (): SnapShotState => ({
    snapshotData: [], // 快照数据
    maxStep: 30, // 最大能够存储的数据数
    curIndex: -1, // 当前所在下标
    isSnapshot: true, // 是否可以保存
  }),
  getters: {},
  actions: {
    initSnapshot() {
      this.snapshotData = [];
      this.curIndex = -1;
      this.isSnapshot = true;
    },
    // 添加快照
    addSnapshot(ele: any) {
      if (this.isSnapshot) {
        this.isFull(); //判断是否溢出 溢出删除一个
        let n = this.snapshotData.length;
        // 当前索引不在尾部，说明进行了撤销，需要删除后面的元素
        if (this.curIndex < n - 1) {
          this.snapshotData.splice(this.curIndex + 1);
        }
        this.snapshotData.push(JSON.stringify(ele));
        if (this.curIndex <= n - 1) {
          this.curIndex++;
        }
        // console.log("snapshotData", this.snapshotData);
        // console.log("length", this.snapshotData.length);
        // console.log("this.curIndex", this.curIndex);
      }
      this.isSnapshot = true;
    },
    // 判断是否溢出
    isFull() {
      if (this.snapshotData.length == this.maxStep) {
        this.snapshotData.shift(0);
      }
    },
    // undo撤销
    undo() {
      if (this.curIndex > 0) {
        this.isSnapshot = false;
        // console.log("this.curIndex", this.curIndex);
        let t = JSON.parse(this.snapshotData[--this.curIndex]);
        return t;
      } else {
        return [];
      }
    },
    // record 恢复
    record() {
      // 判断是不是到尾部，有才可以恢复
      if (this.curIndex < this.snapshotData.length - 1) {
        this.isSnapshot = false;
        let t = JSON.parse(this.snapshotData[++this.curIndex]);
        return t;
      }
    },
  },
});
